package decorator

import (
	"fmt"
	"golang.org/x/net/context"
	"strings"
	"time"
)

// 用于指标判定---设置为接口---后续根据业务实际类型可变
type MetricsClient interface {
	Inc(key string, value int)
}

type queryMetricsDecorator[C, R any] struct { //日志体
	base   QueryHandler[C, R]
	client MetricsClient
}

func (q queryMetricsDecorator[C, R]) Handle(c context.Context, cmd C) (result R, err error) {
	start := time.Now()
	actionName := strings.ToLower(generateActionName(cmd))
	defer func() { //日志函数
		end := time.Since(start)
		q.client.Inc(fmt.Sprintf("query.%s.duration", actionName), int(end.Seconds()))
		if err == nil {
			q.client.Inc(fmt.Sprintf("query.%s.success", actionName), 1)
		} else {
			q.client.Inc(fmt.Sprintf("query.%s.failure", actionName), 2)
		}
	}()
	return q.base.Handle(c, cmd)
}
